<template>
    <div>
        <el-form ref="indexMenu" :model="indexMenu" label-width="80px">
            <el-form-item>
                <el-select class="vipSelect" :disabled="isSelectVip" v-model="vipValue" placeholder="请选择" size="small" @change="selectUserAction">
                    <el-option v-for="item in vipmodule" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-steps :active="indexMenu.activeStep">
                    <el-step title="选择功能区显示的功能" :description="maxModuls"></el-step>
                    <el-step title="确认功能区显示顺序" description="可拖动交换位置"></el-step>
                    <el-step :title="tipsTitle" :description="userAction"></el-step>
                </el-steps>
            </el-form-item>
            <div v-show="usersLable.selecteUsers" style="border-bottom:1px solid #d1dbe5;padding-bottom:20px;">
                <div class="prTips">{{ usersLable.isVipPerf }}</div>
                <el-form-item label="展示功能">
                    <!-- <div style="width:100%;text-align:center;clear:both">{{ usersLable.isVipPerf }}</div> -->
                    <div class="color-list" style="width: 100%;text-align:center">
                        <div class="color-item" v-for="item in usersLable.userArray" :key="item.sortID">
                            <i class="el-icon-menu"></i> {{ item.name }}
                        </div>
                    </div>
                    <div style="width:100%;text-align:left;clear:both">
                        <el-button style="margin-top: 12px;" @click="againSelected">修改</el-button>
                    </div>
                </el-form-item>
            </div>
            <!-- <el-form-item label="选择功能">
                <el-tree
                  :data="tabsModules"
                  show-checkbox
                  :check-strictly="isParents"
                  node-key="id"
                  :default-expanded-keys="[2, 3]"
                  :default-checked-keys="[1]"
                  :props="defaultProps">
                </el-tree>
            </el-form-item> -->
            <div v-show="firModule">
                <div class="prTips">{{ userAction }}</div>
                <el-form-item label="选择功能">
                    <el-checkbox-group v-model="indexMenu.type" :max="max" @change="selectMaxChange">
                        <div v-for="(item, index) in treeTabModule" class="parentModules">
                            <el-checkbox :label="item.id" :name="item.name" :key="item.parentID" :class="item.colors">{{ item.name }}</el-checkbox>
                            <span class="spanModules" v-if="item.children.length > 0" @click="showThisModules(item, $event)">展开</span>
                            <div class="childsModule" v-show="item.isShowClick" v-if="item.children.length > 0">
                                <el-checkbox v-for="(childs, eq) in item.children" :label="childs.id" :name="childs.name" :key="childs.parentID" :class="childs.colors">
                                    {{ childs.name }}
                                </el-checkbox>
                            </div>
                        </div>
                    </el-checkbox-group>
                </el-form-item>
            </div>
            <!-- <el-form-item label="选择功能" v-show="firModule">
                <el-checkbox-group v-model="indexMenu.type" :max="max">
                    <el-checkbox v-for="(item, index) in tabsModules" :label="item.id" :name="item.name" :key="item.parentID" :class="item.colors">{{ item.name }}
                    </el-checkbox>
                </el-checkbox-group>
                <div style="width: 100%;text-align:center;clear:both">{{ userAction }}</div>
            </el-form-item> -->
            <div v-show="secModule">
                <div class="prTips">{{ userAction }}</div>
                <el-form-item label="功能排序">
                    <div class="color-list">
                        <div class="color-item" v-for="color in sortArray" v-dragging="{ item: color, list: sortArray, group: 'color' }" :key="color.sortID">
                            <i class="el-icon-menu"></i> {{ color.name }}
                        </div>
                    </div>
                </el-form-item>
            </div>
            <div v-show="thrModule">
                <div class="prTips" ref="changeTipsUser">{{ usersLable.isCVipPerf }}</div>
                <el-form-item label="展示功能">
                    <div class="color-list">
                        <div class="color-item" v-for="item in sortArray" :key="item.sortID">
                            <i class="el-icon-menu"></i> {{ item.name }}
                        </div>
                    </div>
                </el-form-item>
            </div>
            <el-form-item>
                <el-button v-show="prevBtn" style="margin-top: 12px;" @click="indexSubmit('prev')">{{ prevName }}</el-button>
                <el-button style="margin-top: 12px;" @click="indexSubmit('next')">{{ btnName }}</el-button>
                <!-- <el-button @click="openError()">取消</el-button> -->
            </el-form-item>
        </el-form>
    </div>
</template>
<style scoped>
.el-checkbox {
    margin-left: 15px;
    /*min-width: 100px;*/
}

.vipSelect {
    float: left;
    margin: 10px 20px 0 0;
}

.color-list {
    max-width: 650px;
    float: left;
}

.color-item {
    line-height: 24px;
    min-width: 100px;
    max-width: 120px;
    background: #fff;
    padding: .3rem .5rem;
    color: #324157;
    float: left;
    margin: 8px 10px 0 0;
    border: 1px solid #324157;
    transition: transform .3s;
}

.color-item i {
    margin-right: 10px;
}

.color-item.dragging {
    background-color: #000;
}

.color-item:hover {
    cursor: move;
}

.oneLevelSub {
    color: #2D2F33;
}

.twoLevelSub {
    color: #EB9E05;
}

.el-checkbox__label {
    font-size: 12px;
}

.parentModules {
    min-height: 45px;
}

.parentModules,
.childsModule {
    /*display: inline-block;*/
    float: left;
    /*width: 100%;*/
    width: 150px;
}

.childsModule {
    width: 100%;
    /*display: none;*/
}

.spanModules {
    font-size: 12px;
    color: #EB9E05;
    cursor: pointer;
}

.prTips {
    width: 100%;
    margin: 20px 0 0 0;
    text-align: center;
    font-size: 14px;
    line-height: 36px;
}

.el-step__head.is-text.is-process {
    border-color: #20a0ff;
}

</style>
<script>
export default {
    props: {
        appValueTabs: {}, // 选择的科目信息
        thisName: '', // 各选项卡id
        actName: '', // 被选中的选项卡id
        thisTitle: '', // 各选项卡名字
        options: {}, // 所有科目信息
        tabsModules: {}, // 所有功能模块
        treeTabModule: {}, // 所有树形模块
        max: 0 // 最多可选择多少功能
    },
    data: function() {
        return {
            maxChangedClick: false,
            isParents: true,
            defaultProps: {
                children: 'children',
                label: 'name'
            },
            seriesArray: [],
            indexMenu: {
                activeStep: 0, // 步骤
                type: [], // 默认选中的功能
                allType: [],
                vipType: [],
                noVipType: []
            },
            maxModuls: 0, // 最多配置多少tips
            vipValue: 0, // 默认为全部用户
            isSelectVip: false, // 默认不可选择用户群组
            // vipmodule: [ // 用户群组
            //     {
            //         value: 0,
            //         label: '全部用户（默认）'
            //     }
            // ],
            vipmodule: [{
                    value: 0,
                    label: '全部用户（默认）'
                },
                {
                    value: 1,
                    label: 'VIP用户'
                },
                {
                    value: 2,
                    label: '非VIP用户'
                }
            ],
            userAction: '（全部用户）', // 步骤里面用户类型
            tipsTitle: '', // 步骤里面用户类型选择提示
            btnName: '下一步', // 下一步按钮名称
            prevBtn: false, // 下一步默认隐藏
            prevName: '上一步', // 上一步按钮名称
            usersLable: {
                isVipPerf: '', // 提示lable
                isCVipPerf: '（全部用户）', // 提示lable
                userArray: [],
                selecteUsers: false // 已选用户群组
            },
            firModule: true, // 第一步模块 ==> 默认显示
            secModule: false, // 第二步模块
            thrModule: false, // 第三步模块
            selectArray: [], // 选择的功能已排序id数组
            sortArray: [], // 选择的功能id数组
            submitArray: {
                isPossible: false,
                isAllArrayType: [],
                isVipArray: [],
                isVipArrayType: [],
                isVipArrayInfo: [],
                isNoVipArray: [],
                isNoVipArrayType: [],
                isNoVipArrayInfo: []
            }
        }
    },
    methods: {
        selectMaxChange(len) {
            let _that = this;
            if (len.length < _that.max) {
                _that.maxChangedClick = false;
            }
            if(_that.maxChangedClick){
                _that.$message({
                    message: '最多只能选择' + _that.max + '个功能！',
                    customClass: 'messageClass'
                });
            }
            if(len.length >= _that.max) {
                _that.maxChangedClick = true;
            }
        },
        showThisModules(item, event) {
            let nextDiv = this.getNearEle(event.currentTarget, 0);
            item.isShowClick = !item.isShowClick;
            item.isShowClick? event.currentTarget.innerHTML = '隐藏':event.currentTarget.innerHTML = '展开';
            nextDiv.style.display = item.isShowClick? 'block':'none';
        },
        getNearEle(ele, type) {
            type = type == 1 ? "previousSibling" : "nextSibling";
            var nearEle = ele[type];
            while (nearEle) {
                if (nearEle.nodeType === 1) {
                    return nearEle;
                }
                nearEle = nearEle[type];
                if (!nearEle) {
                    break;
                }
            }
            return null;
        },
        /**
         * 下一步&&上一步
         * @method   indexSubmit
         * @Author   杨少波
         * @DateTime 2017-10-31
         * @Changed  无
         * @param    {dump}    dump   下一步(next)/上一步(默认else)
         * @return   无
         */
        indexSubmit(dump) {
            let _that = this;
            dump === 'next' ? _that.indexMenu.activeStep += 1 : _that.indexMenu.activeStep -= 1;
            // if (_that.indexMenu.activeStep++ > 3) _that.indexMenu.activeStep = 0;
            switch (_that.indexMenu.activeStep) {
                case 1:
                    _that.firModule = false;
                    _that.secModule = true;
                    _that.thrModule = false;
                    _that.prevBtn = true;
                    _that.isSelectVip = true;
                    _that.btnName = "下一步";
                    if (dump === 'next') {
                        _that._addChangeModule();
                    }
                    break;
                case 2:
                    _that.firModule = false;
                    _that.secModule = false;
                    _that.thrModule = true;
                    _that.prevBtn = true;
                    _that.isSelectVip = true;
                    if (_that.vipValue !== 0) {
                        if ((_that.submitArray.isNoVipArray.length > 0 && _that.vipValue === 1) || (_that.submitArray.isVipArray.length > 0 && _that.vipValue === 2)) {
                            _that.btnName = '发布';
                        } else {
                            _that.btnName = '保存';
                        }
                    } else {
                        _that.btnName = '发布';
                    }
                    break;
                case 3:
                    _that._showChangeModule();
                    break;
                default:
                    _that.firModule = true;
                    _that.secModule = false;
                    _that.thrModule = false;
                    _that.prevBtn = false;
                    _that.isSelectVip = false;
                    _that.indexMenu.activeStep = 0;
                    _that.btnName = "下一步";
                    break;
            }
        },
        /**
         * 选择添加功能模块
         * @method   _addChangeModule
         * @Author   杨少波
         * @DateTime 2017-10-31
         * @Changed  无
         */
        _addChangeModule() {
            let _that = this;
            _that.sortArray.splice(0, _that.sortArray.length);
            _that.indexMenu.type.forEach(function(tags) {
                _that.tabsModules.forEach(function(item) {
                    if (item.id === tags) {
                        _that.sortArray.push(item);
                    }
                });
            });
            if (_that.sortArray.length < 1) {
                _that.indexMenu.activeStep = 5;
                _that.indexSubmit('next');
                this.$alert('请选择功能再进行下一步操作');
                return;
            }
            _that.sortArray.forEach(function(item) {
                item.sortID = _that.thisName + '' + item.id;
            });
        },
        /**
         * 点击发布功能
         * @method   _showChangeModule
         * @Author   杨少波
         * @DateTime 2017-10-31
         * @Changed  无
         */
        _showChangeModule() {
            // body
            let _that = this;
            if (_that.btnName === '保存') {
                _that.firModule = true;
                _that.secModule = false;
                _that.thrModule = false;
                _that.prevBtn = false;
                _that.isSelectVip = false;
                _that.indexMenu.activeStep = 0;
                _that.btnName = "下一步";
                _that._releaseModule();
                return;
            }
            this.$confirm('点击确认后将更改用户界面功能区内容', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                _that.firModule = false;
                _that.secModule = false;
                _that.thrModule = true;
                _that.prevBtn = false;
                _that.btnName = '修改';
                _that._releaseModule();
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消发布'
                });
                _that.indexMenu.activeStep = 2;
            });
        },
        againSelected() {
            var _that = this;
            if (_that.usersLable.isVipPerf === 'VIP已选功能') {
                _that.vipValue = 1;
                _that.indexMenu.type = _that.submitArray.isVipArrayType;
            } else {
                _that.vipValue = 2;
                _that.indexMenu.type = _that.submitArray.isNoVipArrayType;
            }
            _that.firModule = true;
            _that.secModule = false;
            _that.thrModule = false;
            _that.prevBtn = false;
            _that.isSelectVip = false;
            _that.indexMenu.activeStep = 0;
            _that.btnName = "下一步";
        },
        changeVipModule(value) {
            var _that = this;
            if (value === 1) {
                _that.indexMenu.type = _that.indexMenu.vipType;
                if (_that.usersLable.isVipPerf !== '') {
                    _that.usersLable.selecteUsers = true;
                }
                if (_that.submitArray.isNoVipArray.length > 0) {
                    _that.usersLable.isVipPerf = '非VIP已选功能';
                    _that.usersLable.isCVipPerf = 'VIP已选功能';
                    _that.usersLable.userArray = _that.submitArray.isNoVipArrayInfo;
                }
                if (_that.submitArray.isVipArrayType.length > 0) {
                    _that.indexMenu.type = _that.submitArray.isVipArrayType;
                }
            } else if (value == 2) {
                _that.indexMenu.type = _that.indexMenu.noVipType;
                if (_that.usersLable.isVipPerf !== '') {
                    _that.usersLable.selecteUsers = true;
                }
                if (_that.submitArray.isVipArray.length > 0) {
                    _that.usersLable.isVipPerf = 'VIP已选功能';
                    _that.usersLable.isCVipPerf = '非VIP已选功能';
                    _that.usersLable.userArray = _that.submitArray.isVipArrayInfo;
                }
                if (_that.submitArray.isNoVipArrayType.length > 0) {
                    _that.indexMenu.type = _that.submitArray.isNoVipArrayType;
                }
            } else {
                _that.indexMenu.type = _that.indexMenu.allType;
                _that.usersLable.selecteUsers = false;
                _that.indexMenu.type = _that.indexMenu.type;
            }
        },
        /**
         * 确认发布事件
         * @method   _releaseModule
         * @Author   杨少波
         * @DateTime 2017-10-31
         * @Changed  无
         */
        _releaseModule() {
            let _that = this;
            _that.selectArray.splice(0, _that.selectArray.length);
            _that.sortArray.forEach(function(item) {
                _that.selectArray.push({ id: item.id, parentID: item.parentID });
            });
            let setModuleUrl = _that.G_AjaxApiTest + "/api/function/setFunction";
            let allUsers = [],
                vipUsers = [],
                notVipUsers = [];
            switch (_that.vipValue) {
                case 1:
                    // vipUsers = _that.selectArray;
                    _that.submitArray.isVipArray.splice(0, _that.submitArray.isVipArray.length);
                    _that.submitArray.isVipArrayType.splice(0, _that.submitArray.isVipArrayType.length);
                    _that.selectArray.forEach(function(item) {
                        _that.submitArray.isVipArray.push(item);
                        _that.submitArray.isVipArrayType.push(item.id);
                    });
                    // _that.submitArray.isVipArray = _that.selectArray;
                    _that.submitArray.isVipArrayInfo.splice(0, _that.submitArray.isVipArrayInfo.length);
                    if (_that.submitArray.isNoVipArray.length > 0) {
                        _that.submitArray.isPossible = true;
                        _that.sortArray.forEach(function(item) {
                            _that.submitArray.isVipArrayInfo.push(item);
                        });
                    } else {
                        _that.usersLable.userArray.splice(0, _that.usersLable.userArray.length);
                        _that.sortArray.forEach(function(item) {
                            _that.usersLable.userArray.push(item);
                            _that.submitArray.isVipArrayInfo.push(item);
                        });
                        _that.vipValue = 2;
                        _that.indexMenu.type = _that.submitArray.isNoVipArrayType;
                        _that.submitArray.isPossible = false;
                    }
                    break;
                case 2:
                    // notVipUsers = _that.selectArray;
                    _that.submitArray.isNoVipArray.splice(0, _that.submitArray.isNoVipArray.length);
                    _that.submitArray.isNoVipArrayType.splice(0, _that.submitArray.isNoVipArrayType.length);
                    _that.selectArray.forEach(function(item) {
                        _that.submitArray.isNoVipArray.push(item);
                        _that.submitArray.isNoVipArrayType.push(item.id);
                    });
                    // _that.submitArray.isNoVipArray = _that.selectArray;
                    _that.submitArray.isNoVipArrayInfo.splice(0, _that.submitArray.isNoVipArrayInfo.length);
                    if (_that.submitArray.isVipArray.length > 0) {
                        _that.submitArray.isPossible = true;
                        _that.sortArray.forEach(function(item) {
                            _that.submitArray.isNoVipArrayInfo.push(item);
                        });
                    } else {
                        _that.usersLable.userArray.splice(0, _that.usersLable.userArray.length);
                        _that.sortArray.forEach(function(item) {
                            _that.usersLable.userArray.push(item);
                            _that.submitArray.isNoVipArrayInfo.push(item);
                        });
                        _that.vipValue = 1;
                        _that.indexMenu.type = _that.submitArray.isVipArrayType;
                        _that.submitArray.isPossible = false;
                    }
                    break;
                default:
                    _that.submitArray.isPossible = true;
                    _that.submitArray.isVipArray.splice(0, _that.submitArray.isVipArray.length);
                    _that.submitArray.isNoVipArray.splice(0, _that.submitArray.isNoVipArray.length);
                    allUsers = _that.selectArray;
                    break;
            }
            if (_that.submitArray.isVipArray.length > 0 || _that.submitArray.isNoVipArray.length > 0) {
                // _that.usersLable.userArray = _that.sortArray;
                // _that.submitArray.isVipArray.length > 0 ? _that.usersLable.isVipPerf = 'VIP已选功能' : _that.usersLable.isVipPerf = '非VIP已选功能';
                _that.usersLable.selecteUsers = true;
                // _that.submitArray.isVipArray.length > 0 ? _that.usersLable.userArray = _that.submitArray.isVipArray : _that.usersLable.userArray = _that.submitArray.isNoVipArray;
            }
            if (!_that.submitArray.isPossible) {
                return;
            }
            let params = {
                // appID: _that.appValueTabs.AppID,
                // appName: _that.appValueTabs.Name,
                info: JSON.stringify(_that.seriesArray),
                pageNum: Number(_that.thisName),
                pageName: _that.thisTitle,
                allUsers: JSON.stringify(allUsers),
                vipUsers: JSON.stringify(_that.submitArray.isVipArray),
                notVipUsers: JSON.stringify(_that.submitArray.isNoVipArray)
            }
            // allUsers[{"id": 0,"parentID": 0}]
            _that.$axios.post(setModuleUrl, _that.$qs.stringify(params)).then(function(response) {
                _that.$message({
                    message: '发布成功',
                    type: 'success'
                });
            }).catch(function(err) {
                _that.$message({
                    message: '接口错误，请联系后台解决！',
                    type: 'error'
                });
                _that.firModule = true;
                _that.secModule = false;
                _that.thrModule = false;
                _that.prevBtn = false;
                _that.isSelectVip = false;
                _that.indexMenu.activeStep = 0;
                _that.btnName = "下一步";
            });
        },
        /**
         * 选择用户群组后更新tips友好提示
         * @method   selectUserAction
         * @Author   杨少波
         * @DateTime 2017-10-31
         * @Changed  无
         * @param    {String}         value 选择的用户类型
         */
        selectUserAction(value) {
            switch (value) {
                case 1:
                    this.userAction = '（VIP用户）';
                    break;
                case 2:
                    this.userAction = '（非VIP用户）';
                    break
                default:
                    this.userAction = '（全部用户）';
                    break
            }
            this.usersLable.isCVipPerf = this.userAction;
            this.changeVipModule(value);
        },
        /**
         * 页面加载后执行
         * @method   onLoad
         * @Author   杨少波
         * @DateTime 2017-10-31
         * @Changed  无
         */
        onLoad() {
            // 初始化用户友好提示
            this.tipsTitle = this.thisTitle + '页面显示功能';
            this.maxModuls = '最多添加' + this.max + '个功能';
            if (!this.appValueTabs.isSubject) {
                this.screenSubjectInfo(this.appValueTabs.Childs);
            }
            if (this.seriesArray.length < 1) {
                this.seriesArray.push({
                    'appID': this.appValueTabs.AppID,
                    'appName': this.appValueTabs.Name
                });
            }
            this.vipValue = 0;
        },
        screenSubjectInfo(opt) {
            let _that = this;
            opt.forEach(function(item) {
                if (item.Childs) {
                    _that.screenSubjectInfo(item.Childs);
                } else {
                    _that.seriesArray.push({
                        'appID': item.AppID,
                        'appName': item.Name
                    });
                }
            });
        },
        /**
         * 获取标签页功能选择信息 && 更新到数据绑定
         * @method   checkIsModuled
         * @Author   杨少波
         * @DateTime 2017-10-31
         * @Changed  无
         */
        checkIsModuled() {
            let _that = this,
                ModuleUrl = _that.G_AjaxApiTest + "/api/function/getFunction";
            _that.$axios.get(ModuleUrl, {
                    params: {
                        appID: _that.appValueTabs.AppID,
                        pageNum: _that.thisName
                    }
                }).then(function(response) {
                    // response.data.data = [1, 22, 2, 23];
                    let jsonData = response.data.data[0];
                    if (jsonData) {
                        // jsonData.allUsers.forEach(function(item){
                        //     _that.indexMenu.type.push(item);
                        // })
                        if(jsonData.allUsers.length > 0){
                            _that.indexMenu.type = jsonData.allUsers;
                            _that.indexMenu.allType = jsonData.allUsers;
                        }
                        if(jsonData.vipUsers.length > 0){
                            _that.indexMenu.vipType = jsonData.vipUsers;
                        }
                        if(jsonData.notVipUsers.length > 0){
                            _that.indexMenu.noVipType = jsonData.notVipUsers;
                        }
                        // response.data.data.forEach(function(ids) {
                        //     _that.indexMenu.type.push(ids.data.);
                        // });
                        _that.isSelectVip = false;
                        // _that.vipmodule = [{
                        //         value: 0,
                        //         label: '全部用户（默认）'
                        //     },
                        //     {
                        //         value: 1,
                        //         label: 'VIP用户'
                        //     },
                        //     {
                        //         value: 2,
                        //         label: '非VIP用户'
                        //     }
                        // ];
                        return;
                    }
                })
                .catch(function(err) {
                    _that.$alert(err, '接口错误，请联系后台解决！', {
                        confirmButtonText: '确定',
                        callback: action => {
                            this.$message({
                                type: 'info',
                                message: `action: ${ action }`
                            });
                        }
                    });
                });
        }
    },
    created: function() {
        // 加载默认执行函数
        this.onLoad();
    },
    mounted: function() {
        // 获取功能模块
        this.checkIsModuled();
    }
}

</script>
